<template>
  <div class="app-container">
    使用子组件
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { importEmployeesAPI } from '@/api/employees'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 上传之前的函数
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 上传成功后执行的函数
    handleSuccess({ results, header }) {
      console.log('读出来的excel的内容是', results, header)
      this.tableData = this.transExcel(results, header)
      this.tableHeader = header
      this.importEmployees()
    },
    // 格式化数据
    transExcel(results, header) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      const cnKeys = Object.keys(mapInfo)
      return results.map(cnObj => {
        const enObj = {}
        cnKeys.forEach(cnkey => {
          const enKey = mapInfo[cnkey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enObj[enKey] = new Date(formatExcelDate(cnObj[cnkey]))
          } else {
            enObj[enKey] = cnObj[cnkey]
          }
        })
        return enObj
      })
    },
    // 批量导入
    async importEmployees() {
      try {
        await importEmployeesAPI(this.tableData)
        // 保存数据
        this.$message.success('批量导入员工成功')
        this.$router.push('/employees')
      } catch (err) {
        console.log('', err)
      }
    }
  }
}
</script>
